<?php
/***
 * Taken from massasi.com,
 * need an efficient way to sandbox the tpl 
 * from eval() and etc, though.
 **/
require_once('../util/consts.php');

// make tpl a singleton and work off of that, perhaps. To eliminate the $this->

class Bitter 
{
  private $tplvars = array();
  private $doctype = "";

  function Bitter($tplfile) {
    $doctype = '<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
                      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">';
    $this->file = Bitter::toTplPath($tplfile);
  }
  function set($name, $value) {
    $this->tplvars[$name] = is_object($value) ? $value->fetch() : $value;
  }
  function fetch($tplfile=null) {
    $tplfile = (!$tplfile) ? $this->file : Bitter::toTplPath($tplfile); 
    extract($this->tplvars);
    ob_start();
    include($tplfile); // XXX error if not
    $contents = ob_get_contents();
    ob_end_clean();
    return $contents;
  }
  function show($tplfile=null) {
    echo $this->fetch($tplfile);
  }
  static function toTplPath($file) {
    return STYLE_TPL_DIR . DIRECTORY_SEPARATOR . STYLE_NAME . DIRECTORY_SEPARATOR . $file . STYLE_FILE_TYPE;
  }
  static function includeTpl($file) {
    include(STYLE_TPL_DIR . DIRECTORY_SEPARATOR . STYLE_NAME . DIRECTORY_SEPARATOR . $file . STYLE_FILE_TYPE);
  }
  static function doctype() {
    return $doctype;
  }
  static function styleDir($file) {
    return STYLE_TPL_DIR . DIRECTORY_SEPARATOR . STYLE_NAME . DIRECTORY_SEPARATOR . $file ;
  }
}

function fetch( $tplfile, $tplvars = null ) {
  global $_TPL;
  if (!$tplvars && is_array($_TPL)) $tplvars = $_TPL;
  else return -1;

  extract($tplvars);
  ob_start();
  include( $tplfile );
  $contents = ob_get_contents();
  ob_end_clean();
  return $contents;
}
function show( $tplfile, $tplvars = null ) {
  echo fetch( $tplfile, $tplvars );
}
function showTpl( $tplfile, $tplvars = null ) {
  echo fetch( toTplFile($tplfile), $tplvars );
}
function toTplFile($file) {
  return STYLE_TPL_DIR . DIRECTORY_SEPARATOR . STYLE_NAME . DIRECTORY_SEPARATOR . $file . STYLE_FILE_TYPE;
}
function prefixStyleDir($file) {
  return STYLE_TPL_DIR . DIRECTORY_SEPARATOR . STYLE_NAME . DIRECTORY_SEPARATOR . $file ;
}
function doctype() {
    return '<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
                      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">';
}

?>
